<script setup>
import SsqSlt from '@/components/SsqSlt/SsqSlt.vue'
import SltFromTable from '@/components/SltFromTable/SltFromTable.vue'
import WuziNz from '@/views/SuperMarket/WuziNz/WuziNz.vue'
import { computed, ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import api from '@/api/index.js'
import { getOptions } from '@/utils/index.js'

const emits = defineEmits(['close', 'init', 'reload'])
const props = defineProps({
  curRow: {
    type: Object,
    default: () => ({})
  }
})
// 弹窗标题
const title = computed(() => (props.curRow.id ? '编辑数据' : '新增数据'))
// 表单数据
const formData = ref({
  goodsId: '',
  orderName: '',
  memberName: '',
  payType: '',
  source: '',
  area: '',
  price: 0,
  unit: '',
  buyQuantity: '',
  payStatus: '',
  remark: ''
})
// 是否显示弹窗
const show = ref(false)
//库存数量
const KcNum = ref()
// 同步表格数据到表单数据内
watch(
  () => props.curRow,
  async (val) => {
    let resObj = {}
    if (props.curRow.id && show.value) {
      const { resultObject } = await api.getXsInfo({ id: props.curRow.id })
      resObj = resultObject
    } else {
      formData.value = {
        goodsId: '',
        orderName: '',
        memberName: '',
        payType: '',
        source: '',
        area: '',
        price: 0,
        unit: '',
        buyQuantity: '',
        payStatus: '',
        remark: ''
      }
    }
    formData.value = { ...formData.value, ...val, ...resObj }
  },
  { deep: true, immediate: true }
)
// 弹窗显示状态切换时触发
const afterOpenChange = (bool) => {
  if (!bool) {
    formData.value = {
      goodsId: '',
      orderName: '',
      memberName: '',
      payType: '',
      source: '',
      area: '',
      price: 0,
      unit: '',
      buyQuantity: '',
      payStatus: '',
      remark: ''
    }
    emits('close')
  }
}
// 提交按钮loading状态
const submitLoading = ref(false)
// 编辑数据
const emitItem = async (info) => {
  if (formData.value.buyQuantity < KcNum.value) {
    formData.value.buyQuantity = 0
    message.warning('商品数量不能低于起步数量')
  } else {
    try {
      submitLoading.value = true
      let params = { ...formData.value, ...info }
      await api.editXs(params)
      message.success('编辑成功')
      show.value = false
      setTimeout(() => {
        submitLoading.value = false
      }, 30)
      emits('reload')
    } catch (error) {
      setTimeout(() => {
        submitLoading.value = false
      }, 30)
    }
  }
}
// 新增数据
const addItem = async (info) => {
  if (formData.value.buyQuantity < KcNum.value) {
    formData.value.buyQuantity = 0
    message.warning('商品数量不能低于起步数量')
  } else {
    try {
      submitLoading.value = true
      let params = { ...formData.value, ...info }
      await api.addXs(params)
      message.success('编辑成功')
      show.value = false
      setTimeout(() => {
        submitLoading.value = false
      }, 30)
      emits('reload')
    } catch (error) {
      setTimeout(() => {
        submitLoading.value = false
      }, 30)
    }
  }
}
// 表单提交，验证通过了
const onFinish = (values) => {
  if (formData.value.id) {
    emitItem(values)
  } else {
    addItem(values)
  }
}
// 验证失败
const onFinishFailed = (errorInfo) => {
  console.log('Failed:', errorInfo)
}
// 打开弹窗
const open = () => {
  show.value = true
}
// 表单节点
const formRef = ref()
// 提交表单
const submit = () => {
  formRef.value.validateFields().then(onFinish).catch(onFinishFailed)
}

const choise = ref(false)
const getRows = (row) => {
  KcNum.value = row?.[0]?.startNum
  formData.value.price = row?.[0]?.price ?? 0
  formData.value.unit = row?.[0]?.unit ?? ''
  if (formData.value.price !== 0 && formData.value.unit) {
    choise.value = true
  } else {
    choise.value = false
  }
}
defineExpose({ open })
</script>

<template>
  <a-drawer
    :maskClosable="false"
    :closable="false"
    destroyOnClose
    v-model:open="show"
    class="custom-class"
    root-class-name="root-class-name"
    :title="title"
    placement="right"
    @after-open-change="afterOpenChange"
  >
    <a-form
      ref="formRef"
      :model="formData"
      layout="vertical"
      autocomplete="off"
      @finish="onFinish"
      @finishFailed="onFinishFailed"
    >
      <a-form-item
        label="订单名称"
        name="orderName"
        :rules="[{ required: true, message: '请输入' }]"
      >
        <a-input v-model:value="formData.orderName" allowClear />
      </a-form-item>
      <a-form-item label="订单来源" name="source" :rules="[{ required: true, message: '请输入' }]">
        <a-input v-model:value="formData.source" allowClear />
      </a-form-item>
      <a-form-item label="选择商品" name="goodsId" :rules="[{ required: true, message: '请选择' }]">
        <a-form-item-rest>
          <SltFromTable
            v-model="formData.goodsId"
            :nameValue="formData.goodsName"
            :component="WuziNz"
            :getRows="getRows"
          />
        </a-form-item-rest>
      </a-form-item>
      <a-form-item
        label="订单客户"
        name="memberName"
        :rules="[{ required: true, message: '请输入' }]"
      >
        <a-input v-model:value="formData.memberName" allowClear />
      </a-form-item>
      <a-form-item label="付款方式" name="payType">
        <a-input v-model:value="formData.payType" allowClear />
      </a-form-item>
      <a-form-item label="销售区域" name="area" :rules="[{ required: true, message: '请输入' }]">
        <a-form-item-rest>
          <SsqSlt v-model="formData.area" />
        </a-form-item-rest>
      </a-form-item>
      <a-form-item
        label="商品价格(元)"
        name="price"
        :rules="[{ required: true, message: '请输入' }]"
      >
        <a-input-number :min="0" v-model:value="formData.price" allowClear :disabled="choise" />
      </a-form-item>
      <a-form-item label="单位" name="unit" :rules="[{ required: true, message: '请选择' }]">
        <a-select
          v-model:value="formData.unit"
          allowClear
          :options="getOptions('unit')"
          :fieldNames="{ label: 'constLabel', value: 'constLabel' }"
          :disabled="choise"
        />
      </a-form-item>
      <a-form-item
        label="商品数量"
        name="buyQuantity"
        :rules="[{ required: true, message: '请输入' }]"
      >
        <a-input-number :min="0" v-model:value="formData.buyQuantity" allowClear />
      </a-form-item>
      <a-form-item label="商品总价" name="recAmount">
        <a-input-number :min="0" :value="formData.buyQuantity * formData.price" disabled />
      </a-form-item>
      <a-form-item
        label="订单状态"
        name="payStatus"
        :rules="[{ required: true, message: '请选择' }]"
      >
        <a-select
          v-model:value="formData.payStatus"
          allowClear
          :options="getOptions('pay_status')"
          :fieldNames="{ label: 'constLabel', value: 'constValue' }"
        />
      </a-form-item>
    </a-form>
    <template #footer>
      <div style="display: flex; gap: 5px">
        <a-button type="primary" html-type="submit" @click="submit" :loading="submitLoading"
          >提交</a-button
        >
        <a-button type="primary" ghost @click="show = false">取消</a-button>
      </div>
    </template>
  </a-drawer>
</template>